﻿using SCADA_SANEST.Helpers;
using SCADA_SANEST.Models;
using SCADA_SANEST.Services;
using SCADA_SANEST.Services.Line_2;
using SCADA_SANEST.ViewModels.Components;
using SCADA_SANEST.ViewModels.Shares;
using SCADA_SANEST.Views.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace SCADA_SANEST.ViewModels.Line_2
{
    public class Npc2ViewModel : BaseViewModel
    {
        public ObservableCollection<PlcSignal> Signals { get; }
        public RelayCommand<object> ShowPlcDetailCommand { get; }

        // Valve ViewModel
        public Air_ValveViewModel AirValveVm { get; }

        public Npc2ViewModel(PlcDeviceStatus backend)
        {
            var service = ServiceManager.GetOrRegisterService("NPC2", new Npc2Service(backend));
            Signals = service.Signals;

            // Tạo AirValve ViewModel
            AirValveVm = new Air_ValveViewModel();

            // Lấy signal Air_Valve từ PLC
            var airValveSignal = Signals.FirstOrDefault(s => s.Name == "BT_KHAN");
            if (airValveSignal != null)
            {
                airValveSignal.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(PlcSignal.Value))
                    {
                        bool newState = false;
                        if (airValveSignal.Value is bool b)
                            newState = b;
                        else if (airValveSignal.Value is int i)
                            newState = i != 0;

                        AirValveVm.IsOpen = newState;
                    }
                };
            }

            ShowPlcDetailCommand = new RelayCommand<object>(_ => true, _ => ShowPlcDetail());
        }

        private void ShowPlcDetail()
        {
            var detailControl = new Views.Common.PlcDataDetail
            {
                DataContext = this
            };

            var window = new Window
            {
                Title = "Chi tiết PLC",
                Content = detailControl,
                Width = 600,
                Height = 400
            };

            window.Show();
        }
    }
}